<?php
namespace app\index\controller;

use app\index\model\User;
use geet\Geet;
use think\Controller;
require_once("../vendor/qq/API/qqConnectAPI.php");
class Login extends Controller
{
    public function index()
    {
        $this->assign('title','登录');
       	return $this->fetch();
    }

    public function create_geet()
    {
        /**
         * 使用Get的方式返回：challenge和capthca_id 此方式以实现前后端完全分离的开发模式 专门实现failback
         * @author Tanxu
         */
        //error_reporting(0);
        $GtSdk = new Geet(CAPTCHA_ID, PRIVATE_KEY);

        $data = array(
            "user_id" => "test", # 网站用户id
            "client_type" => "web", #web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
            "ip_address" => "127.0.0.1" # 请在此处传输用户请求验证时所携带的IP
        );

        $status = $GtSdk->pre_process($data, 1);
        $_SESSION['gtserver'] = $status;
        $_SESSION['user_id'] = $data['user_id'];
        exit($GtSdk->get_response_str());
    }

     public function verify_geet()
    {
        error_reporting(0);

        $GtSdk = new Geet(CAPTCHA_ID, PRIVATE_KEY);

        $data = array(
                "user_id" => $_SESSION['user_id'], # 网站用户id
                "client_type" => "web", #web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
                "ip_address" => "127.0.0.1" # 请在此处传输用户请求验证时所携带的IP
            );


        if ($_SESSION['gtserver'] == 1) {   //服务器正常
            $result = $GtSdk->success_validate($_POST['geetest_challenge'], $_POST['geetest_validate'], $_POST['geetest_seccode'], $data);
            if ($result) {
                return true;
            } else{
                return false;
            }
        }else{  //服务器宕机,走failback模式
            if ($GtSdk->fail_validate($_POST['geetest_challenge'],$_POST['geetest_validate'],$_POST['geetest_seccode'])) {
                return true;
            }else{
                return false;
            }
        }
    }

    public function weixin()
    {

        $appId = "wxbac82045a637c02e";

        $return_url = "http://1o533n8683.imwork.net/index/login/weixin_return";
       
        $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appId."&redirect_uri=".$return_url."&response_type=code&scope=snsapi_base&state=10002#wechat_redirect";

        $this->redirect($url);
    }

    public function weixin_return()
    {
        $code = input('code');

        $appId = "wxbac82045a637c02e";
        $key = "7c320fea54e77a01fcc59ff7060b04e2";

        $url ="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appId."&secret=".$key."&code=".$code."&grant_type=authorization_code";

        $data = file_get_contents($url);
        $data = json_decode($data,true);

        $openid = $data['openid'];


        $user = User::get(['open_id'=>$openid]);

        if($user){

            session('user_id',$user->user_id);
            session('nickname',$user->nickname);
            session('face',$user->face);
            $this->redirect(url('index/user/set'));
        }else{

            $url ="https://api.weixin.qq.com/sns/userinfo?access_token=". $data['access_token']."&openid=". $data['openid']."&lang=zh_CN";

            $user = file_get_contents($url);

            $user = json_decode($user,true);

            $data['nickname'] = $user['nickname'];
            $data['sex'] = $user['sex'] ? '男' : '女';
            $data['city'] = $user['city'];
            $data['face'] = $this->get_img($user['headimgurl']);
            $data['open_id'] = $openid;

            $user = User::create($data);

            if($user){
                session('user_id',$user->user_id);
                session('nickname',$user->nickname);
                session('face',$user->face);
                $this->redirect(url('index/user/set'));
            }

        }

    }

    public function qqlogin()
    {
        $qc = new \QC();

        $qc->qq_login();
    }

    public function qqreturn()
    {
        $qc = new \QC();

        $qc->qq_callback();

        $open_id = $qc->get_openid();

        $user = User::get(['open_id'=>$open_id]);

        if($user){

            session('user_id',$user->user_id);
            session('nickname',$user->nickname);
            session('face',$user->face);
            $this->success('登录成功',url('index/user/set'));
        }else{
            
            $user =  $qc->get_user_info();

            $data['nickname'] = $user['nickname'];
            $data['sex'] = $user['gender'];
            $data['city'] = $user['city'];
            $data['face'] = $this->get_img($user['figureurl_2']);
            $data['open_id'] = $open_id;

            $user = User::create($data);

            if($user){
                session('user_id',$user->user_id);
                session('nickname',$user->nickname);
                session('face',$user->face);
                $this->success('首次登录，请充值！！',url('index/user/set'));
            }
        }

    }

    public function get_img($src=null)
    {
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $src);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        //显示获得的数据
        //
        $dir = "uploads/".date('Ymd');

        is_dir($dir) || mkdir($dir);

        $name = uniqid().'.png';

        $face = $dir."/".$name;

        file_put_contents($face,$data);

        return $face;

    }

    public function out()
    {
    	session(null);

    	 $this->success('退出成功',url('index/index/index'),'',600);

    	 // $this->redirect(url('index/index/index'));

    	// header("Location:".url('index/index/index'));
    }

    public function check()
    {
    	$data = input('post.');


        if(!$this->verify_geet()){
            $this->error('拖动验证没通过');
        }

  //   	// 手动验证
  //   	if(!captcha_check($data['captcha'])){
		//  	$this->error('验证码错误');
		// };

		if(strstr($data['loginName'],'@')){
			$where = ['email' => $data['loginName']];
		}else{
			$where = ['phone' => $data['loginName']];
		}

		$user = User::get($where);

        if($user->status=='禁用'){
            $this->error('帐号被禁用,请联系管理员');
        }

		if($user && $user->password==md5($data['password'])){

			session('user_id',$user->user_id);
			session('nickname',$user->nickname);
			session('face',$user->face);
			$this->success('登录成功');
		}else{
			$this->error('帐号密码不正确Q！！！');
		}
    }
}
